<script setup>

import {onMounted, reactive, ref} from "vue";
import {createEntity} from "./api/EntityApi.js";
import {createFormItems} from './model/EntityConfig.js';
import {initializeCreateFormData, initializeRules, validateForm} from "../../components/EntityOperate.js";

let props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
})

// 定义更新函数
const emit = defineEmits(['update:dialogVisible', 'refresh'])

let formRef = ref(null);
let form = reactive({});
let isSubmitDisabled = ref(true)
const rules = reactive({});

//新增
const create = () => {
  createEntity(form).then(() => {
    emit('update:dialogVisible', false);
    emit('refresh');
  })
}

const cancel = () => {
  for (const key in form) {
    if (form.hasOwnProperty(key)) {
      form[key] = null
    }
  }
  emit('update:dialogVisible', false)
  emit('refresh');
};

const validate = () => {
  validateForm(formRef, isSubmitDisabled);
}

onMounted(() => {
  initializeCreateFormData(createFormItems, form);
  initializeRules(createFormItems, rules);
})
</script>

<template>
  <!--弹窗-新增-->
  <el-dialog v-model="props.dialogVisible" title="详情" width="40%" @close="cancel">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="padding-right:30px ">
      <el-form-item
          v-for="(item, index) in createFormItems"
          :key="index"
          :label="item.label"
          :prop="item.key"
      >
        <el-input
            v-if="item.type === 'string'"
            v-model="form[item.key]"
            :placeholder="item.placeholder"
            autocomplete="off"
            @input="validate"
        />
        <el-input-number
            v-else-if="item.type === 'number'"
            v-model="form[item.key]"
            :placeholder="item.placeholder"
            @change="validate"
        />
        <el-select
            v-else-if="item.type === 'enum'"
            v-model="form[item.key]"
            :placeholder="item.placeholder"
            @change="validate"
        >
          <el-option
              v-for="option in item.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="create" :disabled="isSubmitDisabled">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>